<?php

namespace App\Service\SiteLocation;

use App\Events\SiteLocation\WhiteListEvent;
use App\Models\Common\AmapAreaModel;
use App\Models\Kms\User\KmsUser;
use App\Models\SiteLocation\SiteLocationWhiteListModel;
use App\Models\Traits\KfUid;
use App\Service\BaseService;
use Illuminate\Support\Arr;

class WhiteListService extends BaseService
{
    /**
     * 获得用户ID
     */
    public static function getUserIds($username, $mobile): array
    {
        return KmsUser::query()
            ->when(strlen($username), function ($query) use ($username) {
                $query->where('name', 'like', "%$username%")
                    ->orWhere('nickname', 'like', "%$username%");
            })
            ->when(strlen($mobile), function ($query) use ($mobile) {
                $query->where('mobile', $mobile);
            })
            ->pluck('rmsUserId')
            ->toArray();
    }


    /**
     * 白名单列表
     * @param int $userId
     * @param string $powerType
     * @param int $pageSize
     * @param int $pageNum
     * @return array
     */
    public static function list(int $userId, string $powerType, int $pageSize, int $pageNum): array
    {
        // $search  = false;
        // $userIds = [];
        // 通过用户姓名(模糊搜索)或者电话(精准搜索)获得用户ID
        // if (strlen($name) || strlen($mobile)) {
        //     $search  = true;
        //     $userIds = WhiteListService::getUserIds($name, $mobile);
        // }

        $paginator = SiteLocationWhiteListModel::query()
            ->when($userId, function ($query) use ($userId) {
                $query->where('rmsUserId', $userId);
            })
            ->when(strlen($powerType), function ($query) use ($powerType) {
                switch ($powerType) {
                    case SiteLocationWhiteListModel::POWER_TYPE_APP:
                        $query->whereRaw("JSON_UNQUOTE(JSON_EXTRACT(appPower, '$')) != '[]'");
                        break;
                    case SiteLocationWhiteListModel::POWER_TYPE_PC:
                        $query->whereRaw("JSON_UNQUOTE(JSON_EXTRACT(pcPower, '$')) != '[]'");
                        break;
                    default:
                }
            })
            ->with(['kfFsUserRel'])
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $list = $paginator->map(function (SiteLocationWhiteListModel $whiteListModel) {

            $name = '';
            if ($whiteListModel->kfFsUserRel != null) {
                $name = $whiteListModel->kfFsUserRel->nickname . '(' . $whiteListModel->kfFsUserRel->name . ')';
            }

            $powers = [];
            if (strlen($whiteListModel->appPower) > 0) {
                $appPowerArr = json_decode($whiteListModel->appPower, true);
                if (!empty($appPowerArr)) {
                    $powers[] = [
                        'name'     => 'APP',
                        'province' => self::getRegionName($appPowerArr),
                        'value'    => $appPowerArr,
                    ];
                }
            }
            if (strlen($whiteListModel->pcPower) > 0) {
                $appPowerArr = json_decode($whiteListModel->pcPower, true);
                if (!empty($appPowerArr)) {
                    $powers[] = [
                        'name'     => 'PC',
                        'province' => self::getRegionName($appPowerArr),
                        'value'    => $appPowerArr,
                    ];
                }
            }

            return [
                'id'         => $whiteListModel->id,
                'userId'     => $whiteListModel->rmsUserId,
                'name'       => $name,
                'mobile'     => (string)optional($whiteListModel->kfFsUserRel)->mobile,
                'powers'     => $powers,
                'status'     => $whiteListModel->status,
                'statusText' => $whiteListModel->statusText,
            ];
        })->toArray();

        return [
            'list'     => $list,
            'count'    => $paginator->total(),
            'pageSize' => $pageSize,
            'pageNum'  => $pageNum,
        ];
    }


    /**
     * 通过Code获得区域名称
     */
    public static function getRegionName($codes): array
    {
        // 目前只有省份 简单处理
        $provinceCodes = Arr::collapse($codes);
        return AmapAreaModel::query()
            ->where('level', AmapAreaModel::LEVEL_PROVINCE)
            ->whereIn('code', $provinceCodes)
            ->pluck('label')
            ->toArray();
    }


    /**
     * 添加&修改用户权限
     * @param int $id
     * @param int $userId
     * @param array $appPower
     * @param array $pcPower
     * @param $rmsUserId
     * @return void
     */
    public static function save(int $id, int $userId, array $appPower, array $pcPower, $rmsUserId)
    {
        $userRecordId = (int)SiteLocationWhiteListModel::query()
            ->where('rmsUserId', $userId)
            ->value('id');

        if ($userRecordId != 0 && $id != $userRecordId) {
            self::throwErr('已存在该用户权限,请搜索后编辑');
        }

        if ($id) {
            // 编辑
            $whiteListModel = SiteLocationWhiteListModel::query()
                ->where('id', $id)
                ->first();

            if ($whiteListModel == null) {
                self::throwErr('该记录不存在');
            }
        } else {
            // 添加
            $whiteListModel               = new SiteLocationWhiteListModel();
            $whiteListModel->createdByUid = $rmsUserId;
        }
        $whiteListModel->rmsUserId    = $userId;
        $whiteListModel->appPower     = json_encode($appPower, JSON_UNESCAPED_UNICODE);
        $whiteListModel->pcPower      = json_encode($pcPower, JSON_UNESCAPED_UNICODE);
        $whiteListModel->updatedByUid = $rmsUserId;
        $whiteListModel->save();

        event(new WhiteListEvent());
    }

    /**
     * 更新用户状态
     * @param int $id
     * @param int $status
     * @param int|null $rmsUserId
     * @return void
     */
    public static function updateStatus(int $id, int $status, int $rmsUserId)
    {
        if (!in_array($status, array_keys(SiteLocationWhiteListModel::STATUS_MAPPING))) {
            self::throwErr('状态参数错误');
        }

        $whiteListModel = SiteLocationWhiteListModel::query()
            ->where('id', $id)
            ->first();

        if ($whiteListModel == null) {
            self::throwErr('该记录不存在');
        }

        $whiteListModel->status       = $status;
        $whiteListModel->updatedByUid = $rmsUserId;
        $whiteListModel->save();

        event(new WhiteListEvent());
    }


}